package com.nuedu.corejava.ch14.homework;
/**
 * 1、编写一服务器端程序，实现读取客户端发送过来的一组整数，表现为一组数与数之间用空格隔开的字符串。
 *对这组整数进行排序处理后，返回相应的字符串给客户端，如果数据格式不正确，则返回错误信息，以本机作为服务器。 [必做题]
 * 
 * 
 * @author admin
 *
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class HomeWork {
	public static void main(String[] args) {
		int port = 8888;
		Socket socket = null;
		ServerSocket serverSocket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;

		try {
			//开启监听
			serverSocket = new ServerSocket(port);
			System.out.println("等待客户端连接！");
			//等待客户端连接
			socket = serverSocket.accept();
			System.out.println("客户端连接成功！");
			String words = null;
			String[] strings = null;
			boolean chatting = true;
			while (chatting) {
				boolean isF = false;
				try {
					byte[] buffer = new byte[521];
					//开启客户端的输入输出流
					inputStream = socket.getInputStream();
					outputStream = socket.getOutputStream();
					//读取客户端内容
					int len = inputStream.read(buffer);
					words = new String(buffer, 0, len).trim();
					//将读取内容分开获得数组
					strings = words.split(",");
					//将字符数组转换为数值数组
					for (String i : strings) {
						Integer.parseInt(i);

					}
				} catch (NumberFormatException e) {
					//判断数值格式转换是否异常
					isF = true;
					String wrongString = "格式错误";
					outputStream.write(wrongString.getBytes("ISO-8859-1"));
					System.out.println("格式错误");
				}

				if (!isF) {
					Arrays.sort(strings);
					String putString = "";
					for (String string : strings) {
						System.out.println(string);
						putString += string;
					}
					System.out.println(putString);
					outputStream.write(putString.getBytes("ISO-8859-1"));

				}
				if ("quit".equalsIgnoreCase(words)) {
					chatting = false;
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
